const jwt = require('jsonwebtoken')
const basicAuth = require('basic-auth')

class Auth {}

Auth.USER = 2
Auth.ADMIN = 16
Auth.SUPERADMIN = 32

Auth.verify = level => {
	return async (ctx, next) => {
		let token = basicAuth(ctx.req).name

		let auth = {}
		try {
			auth = Auth.verifyToken(token)
		} catch (err) {
			if (err.name === 'TokenExpiredError') throw new ctx.Exception.TokenExpires({ token })
			throw new ctx.Exception.TokenIllegal({ token })
		}

		if (auth.level < level) throw new ctx.Exception.Forbbiden()

		ctx.auth = { ...auth }

		return next()
	}
}

Auth.signToken = (useid, level) => {
	let token = jwt.sign(
		{
			useid,
			level
		},
		process.env.TOKEN_SECTER,
		{ expiresIn: process.env.TOKEN_EXPIRESIN }
	)

	return token
}

Auth.verifyToken = token => {
	return jwt.verify(token, process.env.TOKEN_SECTER)
}

module.exports = Auth
